# coding:utf-8
import configparser
import os

import requests
import sys
from lxml import etree
import re


class Douyu:
    def __init__(self):
        self.login_url_post = 'https://www.douban.com/login'
        self.desc_url = 'https://www.douban.com/accounts/'
        self.post_data = {
            'form_email': '',
            'redir': 'https://movie.douban.com/',
            'form_password': '',
            'source': 'movie',
            'login': '登录',
            'captcha-solution': '',
            'captcha-id': ''
        }
        self.filename = 'ext/E4_douban_login.html'
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def run(self):
        _user_pswd_cfg = os.environ['user_pswd']
        _cf = configparser.ConfigParser()
        _cf.read(_user_pswd_cfg)
        _email = _cf.get('douban', 'douban_user')
        _pswd = _cf.get('douban', 'douban_pswd')
        self.post_data['form_email'] = _email
        self.post_data['form_password'] = _pswd
        # TODO 验证码处理
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)

        _s = requests.session()
        _response_post = _s.post(self.login_url_post, data=self.post_data, headers=_user_agent, verify=False)
        print(_response_post.url)
        _response_desc = _s.get(self.desc_url)
        print(_response_desc.url)
        _html = _response_desc.content.decode()

        if re.findall(_email, _html):
            with open(self.filename, mode='w', encoding='utf-8')as f:
                f.write(_response_desc)
        else:
            print('not found!')


def main():
    douyu = Douyu()
    douyu.run()


if __name__ == '__main__':
    main()
